</>
)}
*Note: We had to use wrap the links in <> instead of <div> to avoid the two links merging in one column.
For the second link, if the user is not logged in, we show ‘ Login ’ which links to the login component and ‘ Sign
Up ’ which links to the sign up component.
If the user is logged in, it will show ‘ Logout User ’ which links to the logout component.
How do we achieve this conditional rendering? In React, we can use curly braces ‘ {} ’ to put in code. The code is a
ternary statement where if it is true, execute the section after the '?'. If false, execute the section after the colon ':'.
For e.g. if you hardcode user to true, it will always show ‘ Logout User ’ : e.g.
Modify Bold Code
{ user true ? (
<Link class="nav-link">Logout ({user})</Link>
) : (
<>
<Link class="nav-link" to={"/login"}>Login</Link>
<Link class="nav-link" to={"/signup"}>Sign Up</Link>
</>
)}
Let ’ s test our app now to see how it looks like. But before that, we need to enclose our Links in a BrowserRouter.
To do so, in index.js, add:
Modify Bold Code
…
import App from './App';
import { BrowserRouter } from 'react-router-dom';
…
ReactDOM.render(
<React.StrictMode>[DCB5][JL6]
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
…
And if you run your app, it should look like figure 4:
Figure 4
If you change user to false:
Modify Bold Code
{ user false ? (
<Link class="nav-link">Logout ({user})</Link>
) : (
<>
<Link class="nav-link" to={"/login"}>Login</Link>
<Link class="nav-link" to={"/signup"}>Sign Up</Link>
</>
)}
it will show the Login and Sign Up links (fig. 5).
Figure 5
We should of course not leave it hard-coded as true or false. Make sure you change it back to user: